<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
            <el-select icon="el-icon-s-management"  @change="getGoodsInfo" v-model="selectKind" placeholder="地址" class="handle-select mr10">
                    <el-option v-for="item in selectList" :key="item.key" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    :disabled="multipleSelection.length <= 0"
                    @click="delAllSelection()"
                >批量删除</el-button>
                <el-input v-model="content" clearable placeholder="请输入要搜索的内容...商品ID或商品名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="getGoodsInfo">搜索</el-button>
                <el-button type="success" plain icon="el-icon-s-goods" @click="addGoods">新增</el-button>  
                <el-button icon="el-icon-refresh-right" @click="Reset" type="success" size="medium" circle></el-button> 
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
<!--                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>-->
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column label="单价（每500g）">
                    <template slot-scope="scope">￥{{scope.row.price}}</template>
                </el-table-column>
                <el-table-column label="图片(查看大图)" align="center">
                    <template slot-scope="scope">
                        <el-image
                            class="table-td-thumb"
                            :src="imgUrl+scope.row.image"
                            :preview-src-list="[imgUrl+scope.row.image]"
                        ></el-image>
                    </template>
                    
                </el-table-column>
                <el-table-column label="上架状态" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status==0">上架</el-tag>
                        <el-tag type="danger" v-if="scope.row.status==1">下架</el-tag>
                    </template>
                </el-table-column>
 
                <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="delAllSelection(scope.row.id)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                background
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="pageIndex"
                :page-sizes="[5 , 10]"
                :page-size="pageSize"
                :total="totalPage"
                layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
            </div>
        </div>
        <!-- -->
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品ID">
                    <el-input v-model="form.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="商品名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="商品单价">
                    <el-input v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="0">上架</el-radio>
                        <el-radio :label="1">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 新增弹出框 -->
            <el-dialog title="新增商品" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="addFrom" label-width="70px">
<!--                <el-form-item label="商品ID">-->
<!--                    <el-input v-model="addFrom.id" disabled></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="商品名称">
                    <el-input v-model="addFrom.name"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-select v-model="addFrom.type" placeholder="请选择">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片">
                    <el-upload
                        class="avatar-uploader"
                        :action="imageUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品单价">
                    <el-input v-model="addFrom.price"></el-input>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-input v-model="addFrom.details"></el-input>
                </el-form-item>
                <el-form-item label="状态">
<!--                    <el-select v-model="selectValue" placeholder="请选择">-->
<!--                        <el-option v-for="item in options" :key="item.value" :label="item.label"  :value="item.value"></el-option>-->
<!--                    </el-select>-->
                    <el-radio-group v-model="addFrom.radio">
                        <el-radio :label="0">上架</el-radio>
                        <el-radio :label="1">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false  , addFrom = {} ">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
        <!--     -->
    </div>
</template>

<script>
import { mapActions } from "vuex";
import { fetchData } from '../../api/index';
import axios from 'axios'
import * as url from '../../http/api'
import http from '../../http/http'
const imgUrl = 'http://47.108.197.149:8080/images/'
export default {
    name: 'goodstable',
    data() {
        return {
            // imageUrl: 'http://47.108.197.149:8081/file/upload', //上传商品图像的url
            imageUrl: 'http://localhost:8081/file/upload', //上传商品图像的url
            imgUrl : 'http://47.108.197.149:8080/images/',
            tableData: [],    //表数据
            multipleSelection: [],  //多选数组
            delList: [],
            editVisible: false,
            addVisible: false,  //新增dialog是否显示
            pageIndex: 1,
            pageSize: 10,
            totalPage: 0,
            form: {},
            idx: -1,
            id: -1,
            addFrom:{
                radio: 0
            },  //新增表单
            options:[ //新增弹出框选项
                {label:'蔬菜',value:'1'},
                {label:'水果',value:'2'},
                {label:'肉禽',value:'3'},
                {label:'干货',value:'4'},
                {label:'生活日用',value:'5'},
                {label:'海鲜',value:'6'},
                {label:'零食',value:'7'}
            ],
            // selectValue:'', //新增选择上架状态值
            // selectValue2:'', //新增选择上架状态值
            image:'',
            selectKind:'0', //选择查看分类
            selectContent:'',  //选择搜索内容
            content:'',  //搜索内容,
            selectList:[
                {key:'1',label:'全部商品',value:'0'},
                {key:'2',label:'蔬菜',value:'1'},
                {key:'3',label:'水果',value:'2'},
                {key:'4',label:'肉禽',value:'3'},
                {key:'5',label:'干货',value:'4'},
                {key:'6',label:'生活日用',value:'5'},
                {key:'7',label:'海鲜',value:'6'},
                {key:'8',label:'零食',value:'7'}
            ]
        };
    },
    created() {
        this.getGoodsInfo();
    },
    methods: {
        ...mapActions(["mmm"]),
        getGoodsInfo(){  //获取商品、选择分类、搜索商品、重置的统一方法
            http({
                url:url.getGoodsList,
                method:'get',
                params:{
                    'page': this.pageIndex,
                    'limit': this.pageSize,
                    'type':this.selectKind,
                    'key':this.content
                }
            }).then(res =>{
                this.tableData = res.data.page.list
                this.totalPage = res.data.page.totalCount
            }).catch(err =>{
                console.log(err)
            })
        },
        Reset(){   //重置按钮的方法
            http({
                url:url.getGoodsList,
                method:'get',
                params:{
                    'page': this.pageIndex,
                    'limit': this.pageSize,
                    'type':0,
                    'key':''
                }
            }).then(res =>{
                this.tableData = res.data.page.list
                this.totalPage = res.data.page.totalCount
                this.content = ''
                this.selectKind = '0'
            }).catch(err =>{
                console.log(err)
            })
        },
         // 每页数
        sizeChangeHandle (val) {
            this.pageSize = val
            this.pageIndex = 1
            this.getGoodsInfo()
        },
        // 当前页
        currentChangeHandle (val) {
            this.pageIndex = val
            this.getGoodsInfo()
        },
        // 多选(删除)操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection(id) {      //删除
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            // this.multipleSelection = [];
            let ids = id ? [id] : this.multipleSelection.map(item => {
                return item.id
            })
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.error(`删除了${str}`);
                    http({
                        url:url.deleteGoods,
                        method:'post',
                        data:{
                            ids:ids
                        }
                    }).then(res =>{
                        this.getGoodsInfo()
                        console.log(res)
                    }).catch(err =>{
                        console.log(err)
                    })
                })
                .catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;

            http({
                url:url.updateGoods,
                method:'post',
                data:{
                    id:this.form.id,
                    name:this.form.name,
                    price:this.form.price,
                    status:this.form.status,
                }
            }).then(res =>{
                this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                this.getGoodsInfo()
            }).catch(err =>{
                console.log(err)
            })

        },
        //保存新增
        saveAdd(){
            this.addVisible = false;
            let _this = this
            let name = this.addFrom.name
            let type = this.addFrom.type
            let price = this.addFrom.price
            let details = this.addFrom.details
            let status = this.addFrom.radio
            if(name && price && details && status !== ''){
                http({
                    url:url.addGoods,
                    method:'post',
                    data:{
                        name:name,
                        type:type,
                        price:price,
                        details:details,
                        status:status,
                        image:this.image
                    }
                }).then(res =>{
                    this.$message.success(`新增成功！`);
                    _this.addFrom = {};
                    this.getGoodsInfo();
                }).catch(err =>{
                    console.log(err)
                })
            }else{
                this.$message.error("新增商品的名称、单价、描述、上架状态不能为空！请重新填写！")
            }
        },
        // 分页导航
        addGoods(){
            this.addVisible = true;
        },
        handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.image = res.image
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
    }
};
</script>

<style  scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
